'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { messageId, userId } = event;
  
  if (!messageId || !userId) {
    return {
      code: 400,
      msg: '缺少必要参数'
    };
  }

  try {
    // 查询消息是否存在且发送者是当前用户
    const messageResult = await db.collection('chatMessages')
      .where({
        _id: messageId,
        senderId: userId
      })
      .get();

    if (messageResult.data.length === 0) {
      return {
        code: 404,
        msg: '消息不存在或无权撤回'
      };
    }

    const message = messageResult.data[0];
    
    // 检查消息是否超过撤回时间限制（2分钟）
    const messageTime = new Date(message.createTime);
    const now = new Date();
    const timeDiff = now - messageTime;
    const twoMinutes = 2 * 60 * 1000; // 2分钟的毫秒数
    
    if (timeDiff > twoMinutes) {
      return {
        code: 403,
        msg: '消息发送超过2分钟，无法撤回'
      };
    }

    // 更新消息状态为已撤回
    const updateResult = await db.collection('chatMessages')
      .where({
        _id: messageId,
        senderId: userId
      })
      .update({
        status: 'recalled',
        recalledTime: new Date().toISOString(),
        content: '[消息已撤回]'
      });

    if (updateResult.updated === 0) {
      return {
        code: 500,
        msg: '撤回失败'
      };
    }

    return {
      code: 200,
      msg: '消息撤回成功',
      data: {
        messageId: messageId,
        recalledTime: new Date().toISOString()
      }
    };
  } catch (error) {
    console.error('撤回消息失败:', error);
    return {
      code: 500,
      msg: '服务器错误',
      error: error.message
    };
  }
};